package com.sutong.platform.controller;

import cn.hutool.core.util.StrUtil;
import com.sutong.common.result.BaseResponse;
import com.sutong.common.result.ErrorCode;
import com.sutong.platform.common.ResultUtils;
import com.sutong.platform.exception.BusinessException;
import com.sutong.platform.model.dto.shortlink.ShortLinkAddRequest;
import com.sutong.platform.model.vo.ShortLinkVo;
import com.sutong.platform.service.ShortLinkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author sutong
 * @description 短链表Controller
 */
@Slf4j
@RestController
@RequestMapping("/sl")
public class ShortLinkController {

    @Resource
    private ShortLinkService shortLinkService;

    @PostMapping("/generate")
    public BaseResponse<ShortLinkVo> generateShortUrl(@RequestBody ShortLinkAddRequest request) {
        ShortLinkVo res = shortLinkService.generateShortUrl(request.getLongUrl());
        return ResultUtils.success(res);
    }

    @GetMapping("/{shortUrl}")
    public void redirectLongUrl(@PathVariable String shortUrl, HttpServletResponse response) throws IOException {
        String longUrl = shortLinkService.getLongUrl(shortUrl);
        if (StrUtil.isEmpty(longUrl)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        shortLinkService.visitCountPlus(shortUrl);
        response.sendRedirect(longUrl);
    }

}




